<template>
  <div class="selectInput">
    <el-input
      v-model="_value"
      type="text"
      style="width: 100%"
      placeholder="请选择口味"
      clearable
      @blur="inputBlur"
      @focus="isInputBlur = false"
      ref="inputRef"
    />
    <div class="flavorSelect" v-show="!isInputBlur">
      <span v-for="(item, index) in props.optionData" :key="index" class="items" @click="checkOption(item, index)">{{ item[props.label] }}</span>
      <span v-show="props.optionData == null || props.optionData.length === 0" class="none">无数据</span>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, watch, onMounted } from 'vue'
import { debounce } from '@/utils/debounce'
const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  optionData: {
    type: Array<any>,
    default: null
  },
  label: {
    type: String,
    default: 'name'
  },
  debounceInput: {
    type: Boolean,
    default: true
  }
})
const emits = defineEmits<{
  (e: 'input', keyword: string): void
  (e: 'select', item: any, index: number): void
  (e: 'update:modelValue', newVal: string): void
}>()
const isInputBlur = ref(true)
const inputRef = ref()
// 自动聚集，使用el-input export的focus，放在放入外面是不生效的，所以放在了onMounted中
onMounted(() => {
  if (isInputBlur.value) inputRef.value.focus()
})
const _value = ref(props.modelValue)
const inputDebouncedRefresh = debounce((val) => emits('input', val), 460)
// 监听input，并触发更新model:value值与input事件
watch(
  () => _value.value,
  (val) => {
    emits('update:modelValue', val)

    // 点击了选项
    inputDebouncedRefresh(val)
  },
  { deep: true, immediate: true }
)

watch(
  () => props.modelValue,
  (val) => {
    _value.value = val
  },
  { deep: true }
)

const checkOption = (item: any, index: number) => {
  emits('select', item, index)
  inputDebouncedRefresh(item)
  _value.value = item[props.label]
}
// 失去焦点
function inputBlur() {
  // 点击选项，输入框会立即失去焦点，如果立即让其失去焦点，那随之选择项会被隐藏，而“项”的点击事件就会失效
  setTimeout(() => (isInputBlur.value = true), 200)
}
</script>

<style lang="scss" scoped>
.selectInput {
  position: relative;
  width: 100%;
  min-width: 100px;

  .flavorSelect {
    position: absolute;
    z-index: 99;
    width: 100%;
    border: solid 1px #e4e7ed;

    // padding: 0 10px;
    border-radius: 3px;
    text-align: center;
    background: #fff;
    line-height: 30px;

    .items {
      display: inline-block;
      margin: 0 !important;
      width: 100%;
      border-bottom: solid 1px #f4f4f4;
      color: #666;
      cursor: pointer;
      line-height: 35px;

      &:hover {
        background-color: #fffbf0;
      }

      &:active {
        color: #ffc200;
        background-color: #fffbf0;
      }
    }

    .none {
      font-size: 14px;
      color: #7b7c80;
    }
  }
}
</style>
